package com.woniu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.config.MinIOConfig;
import com.woniu.dto.DepartmentQueryDTO;
import com.woniu.entity.Department;
import com.woniu.service.DepartmentService;
import com.woniu.mapper.DepartmentMapper;
import com.woniu.util.MinIODir;
import com.woniu.util.MinIOUtils;
import com.woniu.util.PageData;
import com.woniu.util.ResponseData;
import com.woniu.util.easyExcelUtil.EasyExcelUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.woniu.util.ResponseEnum.INTERFACE_ERR;
import static com.woniu.util.ResponseEnum.PARAM_ERROR;

/**
 * @author Apricity
 * @description 针对表【department(部门表)】的数据库操作Service实现
 * @createDate 2025-02-13 20:16:58
 */
@Service
@AllArgsConstructor
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department>
        implements DepartmentService {
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private MinIOConfig minIOConfig;

    @Override
    public ResponseData<?> queryDepartment(PageData<DepartmentQueryDTO> pageData) {
        PageHelper.startPage(pageData.getPageNum(), pageData.getPageSize());
        //对param进行模糊查询
        List<Department> departments = departmentMapper.queryByForm(pageData.getParam());
        PageInfo<Department> pageInfo = new PageInfo<>(departments);
        return ResponseData.ok(pageInfo);
    }

    @Override
    public ResponseData<?> addDepartment(Department department) {
        save(department);
        return ResponseData.ok();
    }

    @Override
    public ResponseData<?> queryAllDepartment() {
        return ResponseData.ok(lambdaQuery()
                .select(Department::getDepartmentCode, Department::getDepartmentName, Department::getId)
                .eq(Department::getParentDepartmentId, 1)
                .or().isNull(Department::getParentDepartmentId)
                .list());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData<?> batchUpdateDepartment(List<Department> departments) {

        try {
            boolean b = updateBatchById(departments);
            if (b) {
                return ResponseData.ok();
            } else {
                return ResponseData.fail(INTERFACE_ERR);
            }
        } catch (RuntimeException e) {
            //如果出现异常，回滚事务
            e.printStackTrace();
            return ResponseData.fail(INTERFACE_ERR);
        }
    }

    @Override
    public ResponseData<?> batchDeleteDepartment(List<Long> ids) {
        try {
            boolean b = removeByIds(ids);
            if (b) {
                return ResponseData.ok();
            } else {
                return ResponseData.fail(INTERFACE_ERR);
            }
        } catch (RuntimeException e) {
            //如果出现异常，回滚事务
            e.printStackTrace();
            return ResponseData.fail(INTERFACE_ERR);
        }
    }

    @Override
    public ResponseData<?> outDepartmentExcel(HttpServletResponse response, List<Long> ids) throws IOException {
        String fileName;
//        根据ids长度进行导出
        if (ids.isEmpty()) {
            fileName = "demo";
            EasyExcelUtil.writeWithSheetsWeb(response, fileName)
                    .writeModel(Department.class, lambdaQuery().list(), "demo")
                    .finish();
        }

        fileName = "部门详情";
        EasyExcelUtil.writeWithSheetsWeb(response, fileName)
                .writeModel(Department.class, lambdaQuery().in(Department::getId, ids).list(), "sheetName1")
                .finish();
        return ResponseData.ok();
    }

    @Override
    public ResponseData<?> outDepartmentExcelTemplate(HttpServletResponse response) throws IOException {
        String fileName = "部门详情导入模板";
        EasyExcelUtil.writeWithSheetsWeb(response, fileName)
                .writeModel(Department.class, ListUtil.toList(new Department()), "sheetName1")
                .finish();
        return ResponseData.ok();
    }

    @Override
    public ResponseData<?> importDepartmentExcel(MultipartFile file) throws Exception {
        String name =MinIODir.DIR_SYSTEM +file.getName()+UUID.fastUUID(); //防止重名
        //上传到minio服务器
        MinIOUtils.uploadFile(minIOConfig.getBucketName(), name, file.getInputStream());
        //获取文件路径
        String imgUrl= minIOConfig.getFileHost()+ MinIODir.DIR_SYSTEM +minIOConfig.getBucketName()+"/"+name;
        return ResponseData.ok(imgUrl);
    }
}




